package org.vergil.controller;

import org.apache.activemq.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;
import org.vergil.websocket.MyWebSocketHandler;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;

/**
 * Created by vergil on 17-3-25.
 */

@Controller
@RequestMapping(value = "/")
public class IndexController extends BaseController {

    @Autowired
    private MyWebSocketHandler myWebSocketHandler;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private Destination queueDestination;

    private Logger logger = LoggerFactory.getLogger(IndexController.class);

    @RequestMapping(value = "/")
    public ModelAndView index() {
        if (null != user) {
            logger.info(user.getUsername());
        }
          return new ModelAndView("index");
    }

    @RequestMapping(value = "/index")
    public ModelAndView home() {
        sendMessage("for index to mq");
        return new ModelAndView("index");
    }


    public void sendMessage(final String message) {
        System.out.println("---------------生产者发送消息-----------------");
        System.out.println("---------------生产者发了一个消息：" + message);
        jmsTemplate.send(queueDestination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return (Message) session.createTextMessage(message);
            }
        });
    }

}
